import 'package:dio/dio.dart';

class HttpConfig{

  static const bool debug = true;
  static const int timeout = 5000;

  static String baseUrl(){
    return debug ? "https://api.900sui.cn/v1" : "https://api.m.900sui.com/v1";
  }

  static Map<String,dynamic> baseHeaders(){
    return {"channel":"2","device":"3","version":"5.0.0","cid":"321"};
  }
}


class Networking{

  static final BaseOptions baseOptions = BaseOptions(baseUrl: HttpConfig.baseUrl(),connectTimeout: HttpConfig.timeout);
  static final Dio dio = Dio(baseOptions);

  static Future<T> _request<T>(String url,{String method = 'get', Map<String,dynamic> parameters, Interceptor inter}) async {

    final options = Options(method: method, headers: HttpConfig.baseHeaders());

    Interceptor dInter = InterceptorsWrapper(
      onRequest: (request){
        return request;
      },
      onResponse: (response){
        return response;
      },
      onError: (err){
        return err;
      }
    );

    List<Interceptor> inters = [dInter];
    if(inter != null){
      inters.add(inter);
    }

    dio.interceptors.addAll(inters);

    try{
      print("请求链接:${url}参数:${parameters}");
      Response response = await dio.request(url,queryParameters: parameters,options: options);
      return response.data;
    } on DioError catch(e){
      return Future.error(e);
    }
  }

  static Future<T> get<T>(String url, {Map<String,dynamic> parameters, Interceptor inter}) async{
    return _request(url,method: 'get',parameters: parameters,inter: inter);
  }

  static Future<T> post<T>(String url, {Map<String,dynamic> parameters, Interceptor inter}) async{
    return _request(url,method: 'post',parameters: parameters,inter: inter);
  }
}